//Compile: g++ -std=c++11 -pthread -O2 -o nvme_wrr_check nvme_wrr_check.cpp
//run: sudo ./nvme_wrr_check
#include <iostream>
#include <thread>
#include <chrono>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>

// 最简单的WRR测试程序
int main() {
    std::cout << "=== 简单WRR测试 ===" << std::endl;
    
    int fd = open("wrr_test.bin", O_RDWR | O_CREAT, 0644);
    if (fd < 0) {
        std::cout << "无法打开设备" << std::endl;
        return 1;
    }
    
    char buf1[4096], buf2[4096];
    memset(buf1, 'A', 4096);  // 高优先级数据
    memset(buf2, 'B', 4096);  // 低优先级数据
    
    long long high_io = 0, low_io = 0;
    
    std::cout << "测试10秒..." << std::endl;
    
    // 高优先级任务（频繁小IO）
    auto high_task = [&]() {
        auto start = std::chrono::steady_clock::now();
        while (std::chrono::steady_clock::now() - start < std::chrono::seconds(10)) {
            pwrite(fd, buf1, 4096, (rand() % 100) * 4096);
            high_io++;
            std::this_thread::sleep_for(std::chrono::microseconds(100)); // 100us间隔
        }
    };
    
    // 低优先级任务（稀疏大IO）  
    auto low_task = [&]() {
        auto start = std::chrono::steady_clock::now();
        while (std::chrono::steady_clock::now() - start < std::chrono::seconds(10)) {
            pwrite(fd, buf2, 4096, (rand() % 1000) * 4096);
            low_io++;
            std::this_thread::sleep_for(std::chrono::milliseconds(10)); // 10ms间隔
        }
    };
    
    // 启动两个线程
    std::thread t1(high_task);
    std::thread t2(low_task);
    
    // 等待完成
    t1.join();
    t2.join();
    
    close(fd);
    
    // 显示结果
    std::cout << "\n高优先级IO: " << high_io << std::endl;
    std::cout << "低优先级IO: " << low_io << std::endl;
    std::cout << "比例: " << (double)high_io/low_io << ":1" << std::endl;
    
    if (high_io > low_io * 2) {
        std::cout << "✅ WRR仲裁机制工作正常！" << std::endl;
    } else {
        std::cout << "❌ WRR可能未生效" << std::endl;
    }
    
    return 0;
}